<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Gallery extends Controller_Template {
	
	public $template = 'main';
	
	private $json = array('objects' => array());
	
	public function action_index()
	{
		$config = Kohana::$config->load('gallery');
		
		$img_on_page = $config->get('img_on_page');
	
		$page = $this->request->param('page', 0);
		
		//всего изображений
		$img_all = ORM::factory('image')->count_all();
		
		//всего страниц
		$page_all = ceil( $img_all / $img_on_page );
		
		//с какого элемента выборка
		$offset = $page * $img_on_page;
			
		//возвращает данные страницы
		$page_img = ORM::factory('image')
			->order_by( 'id' )
			->offset( $offset )
			->limit( $img_on_page )
			->find_all();
		
		// номера предыдущей и следующая страницы
		//$page_pred = $page-1 <= 0 ? 0: $page - 1;
		$page_next = ($page+1 >= $page_all) ? $page_all: $page+1;
		$page_prev = $page_next-2;
		
		//если ajax
		if ( Request::$current->is_ajax() )
		{
			$this->auto_render = false;
			
			$data = array();
			
			foreach( $page_img as $img ){
				$data[] = array( $img->id, $img->description);
			}
			
			$this->json = array('objects' => array());
			
			$this->json['objects'][] = array( 
				'action' =>'load_page',
				'page_all' => $page_all,
				'page_prev' => $page_prev,
				'page_next' => $page_next,
				'data' => $data
			);
			
			header("Content-type: text/html; charset=utf-8");
			echo json_encode($this->json);			
		}else{
			
			$this->template->content = View::factory('gallery')
				->bind('page_all', $page_all)
				->bind('page_prev', $page_prev)
				->bind('page_next', $page_next)
				->bind('page_img', $page_img);
		}
	}
	
	public function action_edit()
	{
        if ($_POST)
		{
			//--проверка файла на изображение
			$valid_file = Validation::factory($_FILES)
                ->rules('image', array(
                    array('Upload::not_empty'),
                    array('Upload::image'),
                ));

			if($valid_file->check()){
				
				$config = Kohana::$config->load('gallery');
				
				$dir_img = $config->get('dir_img');
				
				$thumb_width = $config['thumb']['width'];
				$thumb_height = $config['thumb']['height'];			
					
				$filename = $_FILES['image']['name'];
				
				// запись в базу
				$Image =  ORM::factory('image');
				$Image->description = $_POST['description'];
				$Image->save();
					
				// сохраняенм изображение на диск с конвертацией в jpg
				$filename = DOCROOT . $dir_img .  $Image->id . '.jpg';
				$original =  Image::factory( $_FILES['image']['tmp_name'] )
					->save( $filename, 80 );
					
				$thumbnail_filename = DOCROOT . $dir_img . '/thumbnail_'. $Image->id . '.jpg';
				Image::factory($_FILES['image']['tmp_name'])
					->resize($thumb_width, $thumb_height, Image::HEIGHT)
					->save( $thumbnail_filename, 80 );

            	$success = "Loaded successfully.";
			}else{
				$errors = $valid_file->errors('gallery');
			}

		}
		
		$this->template->content = View::factory('edit')
			->bind('errors', $errors)
			->bind('success', $success);
	}
	

}
